#include "writer.h"
#include <QDebug>

Writer::Writer(int id, Library *library, int writingTime, int editingTime, int sleepTime) :
    QRunnable(), m_id(id), m_library(library),
    m_writingTime(writingTime),
    m_editingTime(editingTime),
    m_sleepTime(sleepTime)
{
}

void Writer::run()
{
    while (true)
    {
        if (qrand() % 2)
        {
            writeBook();
        }
        else
        {
            editBook();
        }
        QThread::msleep(m_sleepTime);
    }
}

void Writer::writeBook()
{
    book_id_t book = m_library->reserveBookToWrite();
    qDebug() << "Writer " << m_id << " is writing book #" << book;
    QThread::msleep(m_writingTime);
    m_library->publishWrittenBook(book);
    m_writtenBooks.append(book);
    qDebug() << "Writer " << m_id << " finished writing book #" << book;
}

void Writer::editBook()
{
    book_id_t book = m_writtenBooks[qrand() % m_writtenBooks.size()];
    qDebug() << "Writer " << m_id << " is editing book #" << book;
    m_library->takeBookForEditing(book);
    QThread::msleep(m_editingTime);
    m_library->returnEditedBook(book);
    qDebug() << "Writer " << m_id << " finished editing book #" << book;
}
